package com.gem.controller;

import com.gem.domain.Campus;
import com.gem.domain.CampusConn;
import com.gem.domain.User;
import com.gem.service.CampusConnService;
import com.gem.service.UserService;
import com.gem.util.ExcelUtil;
import com.gem.util.MessageUtil;
import com.gem.util.PageUtil;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import static com.gem.util.ExcelUtil.setHSSFValidation;

/**
 * @Author: 玲
 * @Description:
 * @create 2019-10-21 15:03
 * @Modified By:
 */
@Controller
@SuppressWarnings("all")
public class CampusConnController {
    @Autowired
    private CampusConnService service;

    @Autowired
    private UserService userService;

    @RequestMapping("/CampusConn/findAll")
    public String findAll(Integer campusId, Model model,
                          @RequestParam("RcurrentPage") int RcurrentPage,
                          @RequestParam("RpageSize") int RpageSize,
                          @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                          @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        String campusName = service.findCampusName(campusId);
        model.addAttribute("campusName", campusName);
        model.addAttribute("campusId", campusId);
        model.addAttribute("RcurrentPage", RcurrentPage);
        model.addAttribute("RpageSize", RpageSize);
        try {
            PageInfo<CampusConn> pageBeans = service.findAll(campusId, currentPage, pageSize);
            if (pageBeans != null && pageBeans.getList().size() > 0) {
                model.addAttribute("pageBean", pageBeans);
                List<Integer> pageValue = PageUtil.getPageValue(pageBeans.getPages(), currentPage);
                model.addAttribute("pageValue", pageValue);

            } else {
                model.addAttribute("info", "没有数据请先添加！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campus/infoFindAll", "服务器内部错误！请联系管理员！", model);
            return "message";
        }
        return "campus/info_leader";
    }

    @RequestMapping("/CampusConn/saveUI")
    public String saveUI(String campusName, Integer campusId, Model model,
                         @RequestParam("RcurrentPage") int RcurrentPage,
                         @RequestParam("RpageSize") int RpageSize) {
        model.addAttribute("RcurrentPage", RcurrentPage);
        model.addAttribute("RpageSize", RpageSize);
        try {
            List<User> users = userService.findMmembers();
            model.addAttribute("users", users);
            model.addAttribute("campusName", campusName);
            model.addAttribute("campusId", campusId);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/campus/infoFindAll", "服务器内部错误！请联系管理员！", model);
            return "message";
        }
        return "campus/info_leader_insert";
    }

    @RequestMapping("/CampusConn/save")
    public String save(CampusConn campusConn, Integer campusId, Model model,
                       @RequestParam("RcurrentPage") int RcurrentPage,
                       @RequestParam("RpageSize") int RpageSize) {
        model.addAttribute("RcurrentPage", RcurrentPage);
        model.addAttribute("RpageSize", RpageSize);
        try {
            service.save(campusConn);
            MessageUtil.returnInfoPage("3", "/CampusConn/findAll?campusId=" + campusId +
                    "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "添加成功！", model);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/CampusConn/findAll" +
                    "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "服务器内部错误！请联系管理员！", model);
        }
        return "message";
//        return "redirect:/CampusConn/findAll?campusId=" + campusId;
    }


    @RequestMapping("/CampusConn/updateUI")
    public String updateUI(Integer campusConnId, String campusName, Model model,
                           @RequestParam("RcurrentPage") int RcurrentPage,
                           @RequestParam("RpageSize") int RpageSize) {
        model.addAttribute("RcurrentPage", RcurrentPage);
        model.addAttribute("RpageSize", RpageSize);
        try {
            CampusConn campusConn = service.findById(campusConnId);
            model.addAttribute("campusConn", campusConn);
            model.addAttribute("campusName", campusName);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/CampusConn/findAll" +
                    "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "服务器内部错误！请联系管理员！", model);
            return "message";
        }
        return "campus/info_leader_update";
    }

    @RequestMapping("/CampusConn/update")
    public String update(CampusConn campusConn, Model model,
                         @RequestParam("RcurrentPage") int RcurrentPage,
                         @RequestParam("RpageSize") int RpageSize) {
        model.addAttribute("RcurrentPage", RcurrentPage);
        model.addAttribute("RpageSize", RpageSize);
        try {
           if ( service.update(campusConn) == 1){
               MessageUtil.returnInfoPage("3", "/CampusConn/findAll?campusId=" + campusConn.getCampusId() +
                       "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "修改成功！", model);
           }else {
               MessageUtil.returnInfoPage("3", "/CampusConn/findAll?campusId=" + campusConn.getCampusId() +
                       "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "未作修改！", model);
           }
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/CampusConn/findAll", "服务器内部错误！请联系管理员！", model);

        }
        return "message";
    }

    @RequestMapping("/CampusConn/delete")
    @ResponseBody
    public String delete(Integer campusConnId,int currentPageSize, int currentPage, int lastPage){
        try {
            if(service.deleteById(campusConnId)>0){
                if (currentPageSize == 1 && currentPage == lastPage) {
                    return "0";
                }
            }else {
                return "-1";
            }
            return "1";
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }
    }

    @RequestMapping("/CampusConn/deleteAll")
    public String deleteAll(int[] campusConnIds, Model model, Integer campusId,
                            @RequestParam("RcurrentPage") int RcurrentPage,
                            @RequestParam("RpageSize") int RpageSize) {
        model.addAttribute("RcurrentPage", RcurrentPage);
        model.addAttribute("RpageSize", RpageSize);
        try {
            if (campusConnIds != null && campusConnIds.length != 0) {
                service.deleteAll(campusConnIds);
                MessageUtil.returnInfoPage("3", "/CampusConn/findAll?campusId=" + campusId +
                        "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "删除成功！", model);
            } else {
                MessageUtil.returnInfoPage("3", "/CampusConn/findAll?campusId=" + campusId +
                        "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "没有参数传递", model);

            }
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/CampusConn/findAll" +
                    "&RcurrentPage=" + RcurrentPage + "&RpageSize=" + RpageSize, "服务器内部错误！请联系管理员！", model);
        }
        return "message";
    }


    //导出excel模板
    @RequestMapping("/CampusConn/exportTemplate")
    public void exportExcelTemplate(HttpServletResponse response, String campusName, Integer campusId) throws Exception {
        //创建excel工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建sheet对象
        HSSFSheet sheet = workbook.createSheet("Sheet1");

        //创建水平垂直居中的cellStyle单元格样式对象
        HSSFCellStyle cellStyle = ExcelUtil.getTitleStyle(workbook);

        //创建水平垂直居中加粗的cellStyle单元格样式,给表头试用
        HSSFCellStyle cellStyle2 = ExcelUtil.getThStyle(workbook);

        //模板第一行例子展示
        HSSFCellStyle rowStyle = ExcelUtil.getExamplStyle(workbook);

        // 单元格类型日期格式化
        HSSFCellStyle cellStyleDate = ExcelUtil.getDateRedStyle(workbook);

        //创建行对象
        HSSFRow row = null;

        // 将第一行的三个单元格给合并,模板固定
        //注意 java的参数是从0开始 即表示excel中的一行或者第一列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        row = sheet.createRow(0);
        HSSFCell beginCell0 = row.createCell(0);
        beginCell0.setCellValue(campusName + "联系人表");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell0.setCellStyle(cellStyle);

        //第二行的单元格进行合并,语句提示
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 12));
        row = sheet.createRow(1);
        HSSFCell beginCell1 = row.createCell(0);
        beginCell1.setCellValue("请按照模板字段和单元格格式提交数据,日期类型请使用给定格式刷刷一下");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell1.setCellStyle(cellStyle);

        //次数写表头,根据各个页面的进行修改
        HSSFRow headRow = sheet.createRow(2);
        headRow.createCell(0).setCellValue("姓名");
        headRow.createCell(1).setCellValue("性别");
        headRow.createCell(2).setCellValue("职务");
        headRow.createCell(3).setCellValue("渠道专员");
        headRow.createCell(4).setCellValue("联系方式");
        headRow.createCell(5).setCellValue("个人情况");
        headRow.createCell(6).setCellValue("备注");
        headRow.createCell(7).setCellValue("创建时间");
        headRow.createCell(8).setCellValue("修改时间");
        headRow.createCell(9).setCellValue("所属院校id(勿改)");
        headRow.setHeightInPoints(25); // 设置行的高度
        for (int i = 0; i < 10; i++) {
            headRow.getCell(i).setCellStyle(cellStyle2);
        }

        //下拉列表的参数--渠道专员（市场）
        List<User> mmembers = userService.findMmembers();
        String[] personName = new String[mmembers.size()];
        for (int i = 0; i < personName.length; i++) {
            personName[i] = mmembers.get(i).getPersonname();
        }
        //设置当前工作表的设么地方需要下拉,需要自己对着表格设置位置,没有就不需要写
        sheet = setHSSFValidation(sheet, personName, 3, 10000, 3, 3);

        String[] Sex = {"男", "女"};
        sheet = setHSSFValidation(sheet, Sex, 3, 10000, 1, 1);

        String[] Position = {"院长", "副院长", "书记", "主任", "老师", "其他"};
        sheet = setHSSFValidation(sheet, Position, 3, 10000, 2, 2);

        //优化 降低冗余
        HSSFCell cell = null;

        //设置所有列列宽
        for (int i = 0; i < 10; i++) {
            sheet.setColumnWidth(i, 20 * 256);
        } // 设置列的宽度

        //在第四行给一行数据模板,根据对应表的对应字段填写

        row = sheet.createRow(3);

        //第一列,名字
        cell = row.createCell(0);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("姓名");

        cell = row.createCell(1);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("性别");

        cell = row.createCell(2);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("职务");

        cell = row.createCell(3);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("渠道专员");

        cell = row.createCell(4);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("联系方式");

        cell = row.createCell(5);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("个人情况");

        cell = row.createCell(6);
        cell.setCellStyle(rowStyle);
        cell.setCellValue("没啥备注");

        cell = row.createCell(7);
        cell.setCellStyle(cellStyleDate);//改单元格为日期样式
        cell.setCellValue(new Date());//赋值

        cell = row.createCell(8);
        cell.setCellStyle(cellStyleDate);//改单元格为日期样式
        cell.setCellValue(new Date());//赋值

        cell = row.createCell(9);
        cell.setCellStyle(rowStyle);
        cell.setCellValue(campusId);

        OutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=template.xls");

        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

}
